<?php

namespace app\manage\controller;

use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use think\Db;
use think\Exception;
use think\Log;
use think\Queue;
use app\common\model\Merchant;
class Stat extends Base
{
    //线索成本导入
    public function importClueCost()
    {
        $fileInfo = request()->file('file');

        if($fileInfo){
            $info = $fileInfo->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                set_time_limit(300);
                ini_set("memory_limit","2048M");

                $file=ROOT_PATH . 'public' . DS . 'uploads/'.$info->getSaveName();

                // 自动获取文件类型
                $file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
                // 创建读操作
                if ($file_type == 'Xlsx') {
                    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
                } else {
                    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
                }

                // 打开文件、载入excel表格
                $spreadsheet = $reader->load($file);

                // 获取活动工作薄
                $sheet = $spreadsheet->getActiveSheet();


                //获取所有内容并转化为数组
                $data = $sheet->toArray();

                //验证数据
                $title=$data[0];
                $errMsg='表格格式头错误格式应为 投放账户,日期,城市,展示量,点击,消耗金额,转化量,备注,产品';
                if(count($title)<9){
                    return $this->showReturnCode(1011,$errMsg);
                }
                foreach ($title as $k=>$v){
                    if($k==0){
                        if($v!='投放账户'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==1){
                        if($v!='日期'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==2){
                        if($v!='城市'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==3){
                        if($v!='展示量'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==4){
                        if($v!='点击'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==5){
                        if($v!='消耗金额'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==6){
                        if($v!='转化量'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==7){
                        if($v!='备注'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                    if($k==8){
                        if($v!='产品'){
                            return $this->showReturnCode(1011,$errMsg);
                        }
                    }
                }

                $productArr=model('Product')->column('id','name');

                $product=array_keys($productArr);

                unset($data[0]);
                $num=count($data);

                $insertData=[];


                if($this->group_id==7){
                    $accIdArr=model('Account')->where('bind_youhua',$this->uid)->column('id');
                }

                $arrTime=[];

                Db::startTrans();
                foreach ($data as $kk=>$vv){
                    $nowNum=$kk+1;

                    if(empty($vv[0])&&empty($vv[1])&&empty($vv[2])&&empty($vv[3])&&empty($vv[4])&&empty($vv[5])&&empty($vv[6])&&empty($vv[7])){
                        continue;
                    }

//                    if(!is_numeric($vv[3])){
//                        return $this->showReturnCode(1011,'展示量应为数字【'.$vv[3].'】错误:第'.$nowNum.'行');
//                    }
//                    if(!is_numeric($vv[4])){
//                        return $this->showReturnCode(1011,'点击应为数字【'.$vv[4].'】错误:第'.$nowNum.'行');
//                    }
//                    if(!is_numeric($vv[6])){
//                        return $this->showReturnCode(1011,'转化量应为数字【'.$vv[3].'】错误:第'.$nowNum.'行');
//                    }

                    $account=Db::name('account')->where('acc_name',$vv[0])->find();
                    if(empty($account)){
                        return $this->showReturnCode(1011,'账户名【'.$vv[0].'】错误:第'.$nowNum.'行');
                    }


                    if($this->group_id==7){
                        if(!in_array($account['id'],$accIdArr)){
                            return $this->showReturnCode(1011,'权限不足！账户名【'.$vv[0].'】:第'.$nowNum.'行');
                        }
                    }

                    $times=date('Y-m-d',strtotime($vv[1]));


                    if(!in_array($times,$arrTime)){
                        $arrTime[]=$times;
                    }

                    if (strpos($vv[2], '|') !== false) {
                        $city_t = explode('|',$vv[2]);
                    } else {
                        $city_t = explode('-',$vv[2]);
                    }

//                    if(count($city_t) == 3){
//                        $vv[2] = $city_t[1];
//                    }elseif(count($city_t) == 2){
//                        $vv[2] = $city_t[1];
//                    }elseif(count($city_t) == 1){
//                        $vv[2] = $city_t[0];
//                    }
//
//                    if(strpos($vv[2], '文山') !== false){
//                        $city='文山';
//                    }elseif (strpos($vv[2], '凉山') !== false){
//                        $city='凉山';
//                    }elseif (strpos($vv[2], '甘孜') !== false){
//                        $city='甘孜';
//                    }elseif (strpos($vv[2], '恩施') !== false){
//                        $city='恩施';
//                    }elseif (strpos($vv[2], '黔东南') !== false){
//                        $city='黔东南';
//                    }elseif (strpos($vv[2], '巴彦淖尔') !== false){
//                        $city='巴彦淖尔盟';
//                    }elseif (strpos($vv[2], '锡林郭勒') !== false){
//                        $city='锡林郭勒盟';
//                    }else{
                        $city = str_replace('市','',$vv[2] ?? '');
//                    }

                    $city_info = clue_city_transform($city_t);

//                    $city = str_replace('市','',$vv[2] ?? '');

//                    $city_info = Db::name('city')->where(['type'=>2,'name'=>$city])->find();
                    if(!$city_info){
                        return $this->showReturnCode(1011,'城市['.$city.']错误:第'.$nowNum.'行');
                    }
                    if(!in_array($vv[8],$product)){
                        return $this->showReturnCode(1011,'产品['.$vv[8].']错误:第'.$nowNum.'行');
                    }
                    $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
                    $city = $province['id'].'-'.$city_info['id'];

                    $isData=Db::name('ClueCostLog')->where(['account_id'=>$account['id'],'time'=>$times,'city'=>$city])->find();
                    if($isData){
                        if($isData['city']=='3411-3412'||$isData['city']=='3410-3413'){
                            Db::name('ClueCostLog')->where('id',$isData['id'])->inc('exposure_val',$vv[3])->inc('click_val',$vv[4])->inc('money',$vv[5])->inc('transform_val',$vv[6])->update();
                        }else{
                            Db::rollback();
                            return $this->showReturnCode(1011,'导入失败，数据：账户【'.$account['acc_name'].'】日期【'.$times.'】城市【'.$city_info['name'].'】已存在');
                        }
                    }else{
                        //查询进线量
                        $timeStar=strtotime($times.' 00:00:00');
                        $timeEnd=strtotime($times.' 23:59:59');
                        $pro_id=$productArr[$vv[8]];
                        $map['city'] = $city;
                        $map['adv_id'] = $account['adv_id'];
                        $map['pro_id'] = $pro_id;
                        $map['create_time'] = ['between',[$timeStar,$timeEnd]];



                        $clueArrId=Db::name('clue')->where($map)->column('id');
                        $clueNum=count($clueArrId);
                        $trueCost1=bcdiv($vv[5],bcadd(1,$account['clue_rate']/100,4),3);
                        if($clueNum>0){
                            $priceUpdate['is_chengben']=1;
                            $trueCost2=bcdiv($trueCost1,$clueNum,3);//真实成本
                            $priceUpdate['true_price']=$trueCost2;
                            $priceUpdate['xz_true_price']=$trueCost2;
                            $priceUpdate['xz_true_price2']=$trueCost2;

                            $changeCost=bcdiv($vv[5],$clueNum,3);//消耗除以转化
                            $priceUpdate['price']=$changeCost;
                            $priceUpdate['xz_price']=$changeCost;
                            $priceUpdate['xz_price2']=$changeCost;
                            Db::name('clue')->whereIn('id',$clueArrId)->update($priceUpdate);//账户成本
                        }else{
                            $trueCost2=0;
                            $changeCost=0;
                        }
                        //改版了不用了
//                        if($vv[6]>0){
//                            $changeCost=bcdiv($vv[5],$vv[6],3);//消耗除以转化
//                            $priceUpdate['price']=$changeCost;
////                            Db::name('clue')->whereIn('id',$clueArrId)->update(['price'=>$changeCost,'true_price'=>$trueCost2]);//账户成本
//                        }else{
//                            $changeCost=0;
//                        }

//                        if(!empty($priceUpdate)){
//                            Db::name('clue')->whereIn('id',$clueArrId)->update($priceUpdate);//账户成本
//                        }

                        $insertData[]=[
                            'account_id'=>$account['id'],
                            'pro_id'=>$pro_id,
                            'time'=>$times,
                            'city'=>$city,
                            'exposure_val'=>$vv[3],
                            'click_val'=>$vv[4],
                            'money'=>$vv[5],
                            'transform_val'=>$vv[6],
                            'remark'=>$vv[7],
                            'clue_num'=>$clueNum,
                            'change_cost'=>$changeCost,//账户成本
                            'true_cost'=>$trueCost2,//真实成本
                            'true_consume'=>$trueCost1,
                            'create_time'=>time(),
                        ];
                    }
                }
                if($insertData){
                    model('ClueCostLog')->insertAll($insertData);
                    Db::commit();

                    $jobHandlerClassName  = 'app\job\CluePriceAdmin@fire';
                    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                    $jobQueueName     = "CluePriceAdmin";

                    foreach ($arrTime as $at){
                        $timeStar=strtotime($at.' 00:00:00');
                        $timeEnd=strtotime($at.' 23:59:59');

                        $endATime = ['between',[$timeStar,$timeEnd]];

                        $jobData = ['time'=>$endATime];

                        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
                    }

                    return $this->showReturnCode(1001,'导入成功');
                }else{
                    Db::rollback();
                    return $this->showReturnCode(1011,'导入数据不能为空');
                }

            }else{
                return $this->showReturnCode(1009,'上传失败');
            }
        }
    }

    //重新计算成本队列
    public function reCostPriceQueue(){
        $times = input('times','');
        $map=[];
        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['time'] = ['between',[$time_arr[0],$time_arr[1]]];
            $map1['create_time'] =['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
        }else{
            return $this->showReturnCode(1011,'时间不能为空');
        }

        Db::name('clue')->where($map1)->update([
            'price'=>0,
            'true_price'=>0,
            'xz_price'=>0,
            'xz_true_price'=>0,
            'xz_price2'=>0,
            'xz_true_price2'=>0,
            'is_chengben'=>0,
        ]);

        $infos=model('ClueCostLog')
            ->where($map)
            ->chunk(50,function($users) {

                foreach ($users as $logInfo){
                    $account=Db::name('account')->where('id',$logInfo['account_id'])->find();
                    $timeStar=strtotime($logInfo['time'].' 00:00:00');
                    $timeEnd=strtotime($logInfo['time'].' 23:59:59');
                    $map['city'] = $logInfo['city'];
                    $map['account_id'] = $logInfo['account_id'];
                    $map['pro_id'] = $logInfo['pro_id'];

                    $map['create_time'] = ['between',[$timeStar,$timeEnd]];

                    $clueArrId=Db::name('clue')->where($map)->column('id');
                    $clueNum=count($clueArrId);
                    $trueCost1=bcdiv($logInfo['money'],bcadd(1,$account['clue_rate']/100,4),3);
                    if($clueNum>0){

                        $trueCost2=bcdiv($trueCost1,$clueNum,3);//真实成本
                        $changeCost=bcdiv($logInfo['money'],$clueNum,3);//消耗除以转化

                        $priceUpdate=[
                            'price'=>$changeCost,
                            'true_price'=>$trueCost2,
                            'xz_price'=>$changeCost,
                            'xz_true_price'=>$trueCost2,
                            'xz_price2'=>$changeCost,
                            'xz_true_price2'=>$trueCost2,
                            'is_chengben'=>1,
                        ];
                        Db::name('clue')->whereIn('id',$clueArrId)->update($priceUpdate);//账户成本
                    }else{
                        $trueCost2=0;
                        $changeCost=0;
                    }

                    $updateLog=[
                        'clue_num'=>$clueNum,
                        'change_cost'=>$changeCost,//账户成本
                        'true_cost'=>$trueCost2,//真实成本
                        'true_consume'=>$trueCost1,
                        'update_time'=>time(),
                    ];
                    model('ClueCostLog')->where('id',$logInfo['id'])->update($updateLog);
                }
            });



        $infos=model('ClueCostLog')
            ->where($map)
            ->group('time')
            ->column('time');
        $jobHandlerClassName  = 'app\job\CluePriceAdmin@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "CluePriceAdmin";

        foreach ($infos as $at){
            $timeStar=strtotime($at.' 00:00:00');
            $timeEnd=strtotime($at.' 23:59:59');

            $endATime = ['between',[$timeStar,$timeEnd]];

            $jobData = ['time'=>$endATime];
//            dump($jobData);

            Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
        }
        return $this->showReturnCode(1001,'刷新成功');
    }

    //线索成本汇总
    public function clueCostStatistics(){
        $times = input('times','');
        $acc_name = input('acc_name','');
        $adv_id = input('adv_id','');
        $sprovince = input('sprovince','');
        $scity = input('scity','');
        $pro_id = input('pro_id','');
        $orderb = input('orderb/d','');
        $channel_id = input('channel_id/a',0);

        $map = [];
        $map1 = [];

        if(!empty($sprovince)&&empty($scity)){
            $map['a.city']=['like',$sprovince.'-'.'%'];
            $map1['a.city']=['like',$sprovince.'-'.'%'];
        }

        if(!empty($sprovince)&&!empty($scity)){
            $map['a.city']=$sprovince.'-'.$scity;
            $map1['a.city']=$sprovince.'-'.$scity;
        }

        if($adv_id){
            $map['b.adv_id']=$adv_id;
            $map1['b.adv_id']=$adv_id;
        }
        if($acc_name != ''){
            $map['b.acc_name'] = ['like','%'.$acc_name.'%'];
            $map1['b.acc_name'] = ['like','%'.$acc_name.'%'];
        }
        if($pro_id!=''){
            $map['a.pro_id']=$pro_id;
            $map1['a.pro_id']=$pro_id;
        }


        if(!empty($channel_id)){
            if(count($channel_id)==1&&$channel_id[0]==0){

            }else{
                $map['b.channel_id']=['in',$channel_id];
                $map1['b.channel_id']=['in',$channel_id];
            }
        }

        $orderDy='a.id desc';
        if(!empty($orderb)){
            if($orderb==1){
                $orderDy='exposure_val asc';
            }elseif($orderb==2){
                $orderDy='exposure_val desc';
            }elseif($orderb==3) {
                $orderDy = 'click_val asc';
            }elseif($orderb==4) {
                $orderDy = 'click_val desc';
            }elseif($orderb==5) {
                $orderDy = 'money asc';
            }elseif($orderb==6) {
                $orderDy = 'money desc';
            }elseif($orderb==7) {
                $orderDy = 'transform_val asc';
            }elseif($orderb==8) {
                $orderDy = 'transform_val desc';
            }elseif($orderb==9) {
                $orderDy = 'clue_num asc';
            }elseif($orderb==10) {
                $orderDy = 'clue_num desc';
            }elseif($orderb==11) {
                $orderDy = 'change_cost asc';
            }elseif($orderb==12) {
                $orderDy = 'change_cost desc';
            }elseif($orderb==13) {
                $orderDy = 'true_cost asc';
            }elseif($orderb==14) {
                $orderDy = 'true_cost desc';
            }
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['time']=['between',[$time_arr[0], $time_arr[1]]];
            $map1['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
        }

//        dump($map);die;

        $channels=$this->getChannelArray();
        $productArr = Db::name('product')->column('name','id');

        $time_arr = explode(' - ',$times);

        $infos=model('ClueCostLog')->alias('a')->field('a.id,a.time,a.pro_id,sum(exposure_val) exposure_val,sum(click_val) click_val,sum(money) money,sum(transform_val) transform_val,sum(clue_num) clue_num,sum(change_cost) change_cost,sum(true_cost) true_cost,sum(true_consume) true_consume')
            ->join('account b','b.id=a.account_id','LEFT')
            ->where($map)
            ->group('time,pro_id')
            ->order($orderDy)->paginate();
        //合计
        $total=model('ClueCostLog')->alias('a')->field('sum(exposure_val) exposure_val,sum(click_val) click_val,sum(money) money,sum(transform_val) transform_val,sum(clue_num) clue_num,sum(change_cost) change_cost,sum(true_cost) true_cost,sum(true_consume) true_consume')
            ->join('account b','b.id=a.account_id','LEFT')
            ->where($map)
            ->find();

        $total['clue_num']=model('Clue')->alias('a')
            ->join('account b','b.adv_id=a.adv_id','LEFT')
            ->where($map1)->count();


        foreach ($infos as $k=>$v) {
            $infos[$k]['pro_name'] = !empty($v['pro_id'])?$productArr[$v['pro_id']]:'';

            $stime=strtotime($v['time']);
            $etime=strtotime($v['time'].' 23:59:59');
            $infos[$k]['clue_num']=model('Clue')->alias('a')->where('a.pro_id',$v['pro_id'])->whereTime('a.create_time', 'between', [$stime, $etime])->count();

            $infos[$k]['change_cost'] = round($v['change_cost'],2);
            $infos[$k]['true_cost'] = round($v['true_cost'],2);
            $infos[$k]['true_consume'] = round($v['true_consume'],2);

        }
        $province = Db::name('city')->where(['pid'=>1])->select();
        $products = model('Product')->where('status',1)->column('name','id');

//        dump([
//            'channels' => $channels,
//            'province' => $province,
//            'infos' => $infos,
//            'times' => '',
//        ]);die;

        if(!empty($total['exposure_val'])){
            $dianjiRate=bcdiv($total['click_val'],$total['exposure_val'],2)*100;
        }else{
            $dianjiRate=0;
        }

        if(!empty($total['click_val'])){
            $changeRate=bcdiv($total['transform_val'],$total['click_val'],2)*100;
        }else{
            $changeRate=0;
        }


        //账户成本
        if(!empty($total['clue_num'])){
//            $avgChangeMoney=bcdiv($total['money'],$total['transform_val'],2);
            $avgChangeMoney=bcdiv($total['money'],$total['clue_num'],2);
        }else{
            $avgChangeMoney=0;
        }

        //真实成本
        if(!empty($total['clue_num'])){
            $avgConsume=bcdiv($total['true_consume'],$total['clue_num'],2);
        }else{
            $avgConsume=0;
        }

        if(is_array($channel_id)){
            $channel_id=implode(',',$channel_id);
        }else{
            $channel_id=0;
        }

        return $this->fetch('',[
            'channels' => $channels,
            'province' => $province,
            'products' => $products,
            'infos' => $infos,
            'times' => $times,
            'acc_name' => $acc_name,
            'adv_id' => $adv_id,
            'sprovince' => $sprovince,
            'scity' => $scity,
            'exposure_val' => isset($total['exposure_val'])?$total['exposure_val']:0,
            'click_val' => isset($total['click_val'])?$total['click_val']:0,
            'all_money' => isset($total['money'])?$total['money']:0,
            'transform_val' => isset($total['transform_val'])?$total['transform_val']:0,
            'clue_num' => isset($total['clue_num'])?$total['clue_num']:0,
            'change_cost' => isset($total['change_cost'])?floatval($total['change_cost']):0,
            'true_cost' => isset($total['true_cost'])?floatval($total['true_cost']):0,
            'true_consume' => isset($total['true_consume'])?floatval($total['true_consume']):0,
            'pro_id' => $pro_id,
            'dianji_rate' => $dianjiRate,
            'change_rate' => $changeRate,
            'orderb' => $orderb,
            'avgChangeMoney' => $avgChangeMoney,
            'true_consume' => isset($total['true_consume'])?floatval($total['true_consume']):0,
            'avgConsume' => $avgConsume,
            'channel_id' => $channel_id,
        ]);
    }

    //冲正线成本线索数量
//    public function test(){
//
//        $list=Db::name('clue_cost_log')->where('time','<=','2023-11-29')->chunk(50, function($users) {
//            foreach ($users as $info) {
//                $timeStar=strtotime($info['time'].' 00:00:00');
//                $timeEnd=strtotime($info['time'].' 23:59:59');
//                $pro_id=$info['pro_id'];
//                $map['city'] = $info['city'];
//                $map['adv_id'] = Db::name('account')->where('id',$info['account_id'])->value('adv_id');
//                $map['pro_id'] = $pro_id;
//                $map['create_time'] = ['between',[$timeStar,$timeEnd]];
//
//                $clueArrId=Db::name('clue')->where($map)->column('id');
//                $clueNum=count($clueArrId);
//                $trueCost1=$info['true_consume'];
//                if($clueNum>0){
//                    $trueCost2=bcdiv($trueCost1,$clueNum,3);
//                }else{
//                    $trueCost2=0;
//                }
//                if($info['transform_val']>0){
//                    $changeCost=$info['change_cost'];
//                    Db::name('clue')->whereIn('id',$clueArrId)->update(['price'=>$changeCost]);
//                }else{
//                    $changeCost=0;
//                }
//
//                Db::name('clue_cost_log')->where('id',$info['id'])->update(['true_cost'=>$trueCost2,'clue_num'=>$clueNum]);
//
//            }
//            echo 1;
//
//        });
//
////        //查询进线量
////        $timeStar=strtotime($times.' 00:00:00');
////        $timeEnd=strtotime($times.' 23:59:59');
////        $pro_id=$productArr[$vv[8]];
////        $map['city'] = $city;
////        $map['adv_id'] = $account['adv_id'];
////        $map['pro_id'] = $pro_id;
////        $map['create_time'] = ['between',[$timeStar,$timeEnd]];
////
////        $clueArrId=Db::name('clue')->where($map)->column('id');
////        $clueNum=count($clueArrId);
////        $trueCost1=bcdiv($vv[5],bcadd(1,$account['clue_rate']/100,4),3);
////        if($clueNum>0){
////            $trueCost2=bcdiv($trueCost1,$clueNum,3);
////        }else{
////            $trueCost2=0;
////        }
////        if($vv[6]>0){
////            $changeCost=bcdiv($vv[5],$vv[6],3);
////            Db::name('clue')->whereIn('id',$clueArrId)->update(['price'=>$changeCost]);
////        }else{
////            $changeCost=0;
////        }
////
////        $insertData[]=[
////            'account_id'=>$account['id'],
////            'pro_id'=>$pro_id,
////            'time'=>$times,
////            'city'=>$city,
////            'exposure_val'=>$vv[3],
////            'click_val'=>$vv[4],
////            'money'=>$vv[5],
////            'transform_val'=>$vv[6],
////            'remark'=>$vv[7],
////            'clue_num'=>$clueNum,
////            'change_cost'=>$changeCost,
////            'true_cost'=>$trueCost2,
////            'true_consume'=>$trueCost1,
////            'create_time'=>time(),
////        ];
//    }

    //线索成本明细
    public function clueCost(){
        $times = input('times','');
        $acc_name = input('acc_name','');
        $adv_id = input('adv_id','');
        $sprovince = input('sprovince','');
        $scity = input('scity','');
        $pro_id = input('pro_id','');
        $orderb = input('orderb/d','');
        $channel_id = input('channel_id/a',0);
        $type = input('type',0);//0默认1账户
        $is_kong = input('is_kong','');
        $cityname = input('cityname','');

        $youhua_id = input('youhua_id','');
        $map = [];

        if(!empty($sprovince)&&empty($scity)){
            $map['a.city']=['like',$sprovince.'-'.'%'];
        }

        if(!empty($sprovince)&&!empty($scity)){
            $map['a.city']=$sprovince.'-'.$scity;
        }

        if($adv_id){
            $map['b.adv_id']=$adv_id;
        }
        if($acc_name != ''){
            $map['b.acc_name'] = ['like','%'.$acc_name.'%'];
        }
        if($pro_id!=''){
            $map['a.pro_id']=$pro_id;
        }

        if(!empty($channel_id)){
            if(count($channel_id)==1&&$channel_id[0]==0){

            }else{
                $map['b.channel_id']=['in',$channel_id];
            }
        }

        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['a.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['a.city']=0;
            }
        }

        if($is_kong=='1'){
            $map['a.money']=['>',0];
            $map['a.transform_val']=['=',0];
            $map['a.clue_num']=['>',0];
        }elseif ($is_kong=='2'){
            $map['a.money']=['>',0];
            $map['a.transform_val']=['=',0];
            $map['a.clue_num']=['=',0];
        }elseif ($is_kong=='3'){
            $map['a.money']=['>',0];
            $map['a.transform_val']=['>',0];
            $map['a.clue_num']=['=',0];
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['a.time'] = ['between',[$time_arr[0],$time_arr[1]]];
        }

        if($this->group_id==7){
            $accIdArr=model('Account')->where('bind_youhua',$this->uid)->column('id');
            if(empty($accIdArr)){
                $map['b.id']=0;
            }else{
                $map['b.id']=['in',$accIdArr];
            }
        }

        $orderDy='a.id desc';
        if(!empty($orderb)){
            if($orderb==1){
                $orderDy='exposure_val asc';
            }elseif($orderb==2){
                $orderDy='exposure_val desc';
            }elseif($orderb==3) {
                $orderDy = 'click_val asc';
            }elseif($orderb==4) {
                $orderDy = 'click_val desc';
            }elseif($orderb==5) {
                $orderDy = 'money asc';
            }elseif($orderb==6) {
                $orderDy = 'money desc';
            }elseif($orderb==7) {
                $orderDy = 'transform_val asc';
            }elseif($orderb==8) {
                $orderDy = 'transform_val desc';
            }elseif($orderb==9) {
                $orderDy = 'clue_num asc';
            }elseif($orderb==10) {
                $orderDy = 'clue_num desc';
            }elseif($orderb==11) {
                $orderDy = 'change_cost asc';
            }elseif($orderb==12) {
                $orderDy = 'change_cost desc';
            }elseif($orderb==13) {
                $orderDy = 'true_cost asc';
            }elseif($orderb==14) {
                $orderDy = 'true_cost desc';
            }
        }

        //优化师
        if($youhua_id!=''){
            $map['b.bind_youhua']=$youhua_id;
        }

//        dump($map);die;

        $channels=$this->getChannelArray();
        $productArr = Db::name('product')->column('name','id');


        if($type==1){

            $infos=model('ClueCostLog')->alias('a')->field('a.pro_id,sum(exposure_val) exposure_val,sum(click_val) click_val,sum(money) money,sum(transform_val) transform_val,sum(clue_num) clue_num,sum(change_cost) change_cost,sum(true_cost) true_cost,sum(true_consume) true_consume,b.acc_name,b.acc_desc,b.adv_id,b.channel_id')
                ->join('account b','b.id=a.account_id','LEFT')
                ->where($map)
                ->group('a.account_id,a.pro_id')
                ->order($orderDy)->paginate();
            $total=model('ClueCostLog')->alias('a')->field('sum(exposure_val) exposure_val,sum(click_val) click_val,sum(money) money,sum(transform_val) transform_val,sum(clue_num) clue_num,sum(change_cost) change_cost,sum(true_cost) true_cost,sum(true_consume) true_consume')
                ->join('account b','b.id=a.account_id','LEFT')
                ->where($map)
                ->find();


            foreach ($infos as $k=>$v) {
                $infos[$k]['pro_name'] = !empty($v['pro_id'])?$productArr[$v['pro_id']]:'';

                $infos[$k]['channel_name'] = $channels[$v['channel_id']];
                if($v['transform_val']>0){
                    $infos[$k]['change_cost']=round(bcdiv($v['money'],$v['transform_val'],3),2);
                }else{
                    $infos[$k]['change_cost'] = 0;
                }
//                $infos[$k]['true_cost'] = round($v['true_cost'],2);
                $infos[$k]['true_consume'] = round($v['true_consume'],2);
                if($v['clue_num']>0){
                    $infos[$k]['true_cost']=round(bcdiv($v['true_consume'],$v['clue_num'],3),2);
                }else{
                    $infos[$k]['true_cost']=0;
                }

            }

        }else{

            $infos=model('ClueCostLog')->alias('a')->field('a.*,b.acc_name,b.acc_desc,b.adv_id,b.channel_id')
                ->join('account b','b.id=a.account_id','LEFT')
                ->where($map)->order($orderDy)->paginate();
            $total=model('ClueCostLog')->alias('a')->field('sum(exposure_val) exposure_val,sum(click_val) click_val,sum(money) money,sum(transform_val) transform_val,sum(clue_num) clue_num,sum(change_cost) change_cost,sum(true_cost) true_cost,sum(true_consume) true_consume')
                ->join('account b','b.id=a.account_id','LEFT')
                ->where($map)
                ->find();


            foreach ($infos as $k=>$v) {
                $infos[$k]['pro_name'] = !empty($v['pro_id'])?$productArr[$v['pro_id']]:'';
                if ($v['city'] != '') {
                    $ids = explode('-', $v['city']);
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if ($prov == $city) {
                        $infos[$k]['city'] = $prov;
                    } else {
                        $infos[$k]['city'] = $prov . '-' . $city;
                    }
                }

                $infos[$k]['channel_name'] = $channels[$v['channel_id']];
                $infos[$k]['change_cost'] = round($v['change_cost'],2);
                $infos[$k]['true_cost'] = round($v['true_cost'],2);
                $infos[$k]['true_consume'] = round($v['true_consume'],2);

            }
        }
//        dump($map);
//        dump($infos);die;


        $province = Db::name('city')->where(['pid'=>1])->select();
        $products = model('Product')->where('status',1)->column('name','id');

//        dump([
//            'channels' => $channels,
//            'province' => $province,
//            'infos' => $infos,
//            'times' => '',
//        ]);die;

        if(!empty($total['exposure_val'])){
            $dianjiRate=bcdiv($total['click_val'],$total['exposure_val'],2)*100;
        }else{
            $dianjiRate=0;
        }

        if(!empty($total['click_val'])){
            $changeRate=bcdiv($total['transform_val'],$total['click_val'],2)*100;
        }else{
            $changeRate=0;
        }


        //账户成本
        if(!empty($total['transform_val'])){
            $avgChangeMoney=bcdiv($total['money'],$total['transform_val'],2);
        }else{
            $avgChangeMoney=0;
        }

        //真实成本
        if(!empty($total['clue_num'])){
            $avgConsume=bcdiv($total['true_consume'],$total['clue_num'],2);
        }else{
            $avgConsume=0;
        }

        if(is_array($channel_id)){
            $channel_id=implode(',',$channel_id);
        }else{
            $channel_id=0;
        }

        $youhua = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
            ->join('admin b','a.uid=b.id')
            ->where(function ($q){
                $q->where('a.group_id',7);
            })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();

        return $this->fetch('',[
            'channels' => $channels,
            'province' => $province,
            'products' => $products,
            'infos' => $infos,
            'times' => $times,
            'acc_name' => $acc_name,
            'adv_id' => $adv_id,
            'sprovince' => $sprovince,
            'scity' => $scity,
            'exposure_val' => isset($total['exposure_val'])?$total['exposure_val']:0,
            'click_val' => isset($total['click_val'])?$total['click_val']:0,
            'all_money' => isset($total['money'])?$total['money']:0,
            'transform_val' => isset($total['transform_val'])?$total['transform_val']:0,
            'clue_num' => isset($total['clue_num'])?$total['clue_num']:0,
            'change_cost' => isset($total['change_cost'])?floatval($total['change_cost']):0,
            'true_cost' => isset($total['true_cost'])?floatval($total['true_cost']):0,
            'pro_id' => $pro_id,
            'dianji_rate' => $dianjiRate,
            'change_rate' => $changeRate,
            'orderb' => $orderb,
            'avgChangeMoney' => $avgChangeMoney,
            'true_consume' => isset($total['true_consume'])?floatval($total['true_consume']):0,
            'avgConsume' => $avgConsume,
            'channel_id' => $channel_id,
            'type' => $type,
            'is_kong' => $is_kong,
            'cityname' => $cityname,
            'youhua' => $youhua,
            'youhua_id' => $youhua_id
        ]);
    }

    //获取账户
    public function getAccount()
    {
        // 查询条件start
        $channel_id = input('pid',0);

        $map = [];
        if($channel_id != 0){
            $map['channel_id'] = $channel_id;
        }

        // 查询条件end

        $infos = model('Account')->getListByMap($map, 'id,acc_name,acc_desc,adv_id', false);

        return self::showJsonReturnCodeData('1001',$infos,'');
    }

    //保存每日账户成本
    public function saveClueCost(){
        if(request()->isAjax()){
            try{
                $post = input('post.');

                if(empty($post['province'])||empty($post['city'])){
                    return self::showReturnCode(1011,'请选择城市');
                }

                $save_data=[
                    'account_id'=>$post['account'],
                    'time'=>$post['dtime'],
                    'pro_id'=>$post['pro_id'],
                    'exposure_val'=>$post['exposure_val'],
                    'click_val'=>$post['click_val'],
                    'money'=>$post['money'],
                    'transform_val'=>$post['transform_val'],
                    'clue_num'=>$post['clue_num'],
                    'change_cost'=>$post['change_cost'],
                    'true_cost'=>$post['true_cost'],
                    'remark'=>$post['remark'],
                ];


                $save_data['city'] = $post['province'].'-'.$post['city'];

                if(!empty($post['id'])){
                    $save_data['id']=$post['id'];
                }

                $result = $this->editData(false,'','ClueCostLog',$save_data);
                if($result['code'] == 1001){
                    $result['msg'] = '保存成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'账户【'.$save_data['account_id'].'】日期【'.$save_data['time'].'】保存成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    //获取一条编辑
    public function editClueCost()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $info = model('ClueCostLog')->getInfoByMap(['id'=>$id]);
        $merchant=model('Account')->field('id,acc_name,acc_desc,adv_id,channel_id')->find($info['account_id']);
        $info['acc_id']=$merchant['id'];
        $info['acc_name']=$merchant['acc_name'];
        $info['acc_desc']=$merchant['acc_desc'];
        $info['adv_id']=$merchant['adv_id'];
        $info['channel_id']=$merchant['channel_id'];
        if($info['city'] != 0){
            $ids = explode('-',$info['city']);
            $info['prov'] = $ids[0];
            $info['city'] = $ids[1];
            $info['city_name'] = $this->getCityName($ids[1]);
        }else{
            $info['prov'] = 0;
            $info['city'] = 0;
            $info['city_name'] = '';
        }
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    //删除成本记录
    public function delClueCost(){
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = 'ClueCostLog';

            $info=model($model)->where('id',$id)->find();
            if($info['type']==2){
                return $this->showReturnCode(1009,'无法删除');
            }

            $res = model($model)->destroy($id);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001,'删除成功');
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }

    }

    //删除成本记录
    public function delClueCostAll(){
        if($this->request->isAjax()){

            $times = input('times','');
            $acc_name = input('acc_name','');
            $adv_id = input('adv_id','');
            $sprovince = input('sprovince','');
            $scity = input('scity','');
            $pro_id = input('pro_id','');
            $orderb = input('orderb/d','');
            $youhua_id = input('youhua_id','');

            $map = [];

            if(!empty($sprovince)&&empty($scity)){
                $map['city']=['like',$sprovince.'-'.'%'];
            }

            if(!empty($sprovince)&&!empty($scity)){
                $map['city']=$sprovince.'-'.$scity;
            }

            if($adv_id){
//                $map['b.adv_id']=$adv_id;
                $map['account_id']=Db::name('account')->where('adv_id',$adv_id)->value('id');

            }
            if($acc_name != ''){
//                $map['b.acc_name'] = ['like','%'.$acc_name.'%'];
                $accId=Db::name('account')->where('acc_name','like','%'.$acc_name.'%')->column('id');
                if($accId){
                    $map['account_id']=['in',$accId];
                }else{
                    $map['account_id']=0;
                }
            }
            if($pro_id!=''){
                $map['pro_id']=$pro_id;
            }

            if($times != ''){
                $time_arr = explode(' - ',$times);
                $map['time'] = ['between',[$time_arr[0],$time_arr[1]]];
            }

            $map['type']=1;

            //优化师
            if($youhua_id!=''){
                $account_ids = \db('account')->where('bind_youhua', $youhua_id)->column('id');
                $map['account_id'] = ['in', $account_ids];
            }

            if(empty($map)){
                return $this->showReturnCode(1009,'请先查询再删除！');
            }


//            if($times != ''){
//                $time_arr = explode(' - ',$times);
//                $res = model('ClueCostLog')->where($map)
//                    ->whereTime('time', 'between', [$time_arr[0], $time_arr[1]])
//                    ->delete();
//            }else{
//
//            }
//            dump($map);
//            $list=model('ClueCostLog')->where($map)->select();
//            dump($list);die;
            $res = model('ClueCostLog')->where($map)->delete();
//            dump($res);die;
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功');
                return $this->showReturnCode(1001,'删除成功');
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }

    }

    // 费用统计
    public function prices()
    {
        $mer_name = input('mer_name','');
        $mobile = input('mobile','');
        $times = input('times','');
        $orderb = input('orderb','');

        $map = [];
        $map1 = [];
        $map2 = [];
        $map3 = [];
        $map4 = '';
        $map5 = '';
        $map6 = '';
        $map7 = '';

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map1['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
            $map3['b.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
            $map4 = ' AND b.create_time >= '.strtotime($time_arr[0]).' AND b.create_time <= '.strtotime($time_arr[1]);
            $map5 = ' AND c.create_time >= '.strtotime($time_arr[0]).' AND c.create_time <= '.strtotime($time_arr[1]);
            $map6 = ' AND d.create_time >= '.strtotime($time_arr[0]).' AND d.create_time <= '.strtotime($time_arr[1]);
            $map7 = ' AND e.create_time >= '.strtotime($time_arr[0]).' AND e.create_time <= '.strtotime($time_arr[1]);
        }

        if(in_array($this->group_id,[4,5])){
            $map['bind_aid|weihu_aid']=$this->uid;
        }

        if ($mer_name != '') {
            $map['mer_name'] = ['like', '%' . $mer_name . '%'];
        }

        if (!empty($mobile)) {
            $map['phone|username'] = ['like', '%' . $mobile . '%'];
        }

        if (!empty($mer_name) || !empty($mobile)) {
            $mInfo = model('Merchant')->where($map)->column('id');
            if ($mInfo) {
                $map2['mer_id'] = ['in', $mInfo];
            } else {
                $map2['mer_id'] = 0;
            }
        }

        $orderDef='a.id desc';
        if($orderb==1){
            $orderDef='prices asc';
        }elseif ($orderb==2){
            $orderDef='prices desc';
        }elseif ($orderb==3){
            $orderDef='balance asc';
        }elseif ($orderb==4){
            $orderDef='balance desc';
        }elseif ($orderb==5){
            $orderDef='moneys asc';
        }elseif ($orderb==6){
            $orderDef='moneys desc';
        }elseif ($orderb==7){
            $orderDef='fzmoney asc';
        }elseif ($orderb==8){
            $orderDef='fzmoney desc';
        }elseif ($orderb==9){
            $orderDef='id asc';
        }elseif ($orderb==10){
            $orderDef='id desc';
        }elseif ($orderb==11){
            $orderDef='fwmoney asc';
        }elseif ($orderb==12){
            $orderDef='fwmoney desc';
        }

        $chargeAll = model('Charge')->field('sum(money) moneys,sum(fz_money) fzmoney,sum(fw_money) fwmoney')->where($map2)->where($map1)->find();
//        $chargeAll2 = model('ChargeFw')->field('sum(money) moneys')->where($map2)->where($map1)->find();
        $moneys=!empty($chargeAll['moneys'])?$chargeAll['moneys']:0;
        $fzmoney=!empty($chargeAll['fzmoney'])?$chargeAll['fzmoney']:0;
        $fwmoney=!empty($chargeAll['fwmoney'])?$chargeAll['fwmoney']:0;

        $clueMoneyAll = model('ClueLog')->where($map2)->where($map1)->sum('price');
        $mAll = model('Merchant')->where($map)->sum('balance');

        $infos = model('Merchant')->alias('a')->field('a.id,username,mer_name,a.status,balance,balance2,balance3,(SELECT sum(price) from wy_clue_log as b where b.mer_id=a.id'.$map4.') as prices,(SELECT sum(money) from wy_charge as c where c.mer_id=a.id'.$map5.') as moneys,(SELECT sum(fz_money) from wy_charge as d where d.mer_id=a.id'.$map6.') as fzmoney,(SELECT sum(fw_money) from wy_charge as e where e.mer_id=a.id'.$map7.') as fwmoney')
//            ->join('clue_log b','a.id=b.mer_id','LEFT')

            ->where($map)
//            ->where($map3)
            ->order($orderDef)
            ->paginate();

        foreach ($infos as $k=>$v){
            //消耗
//            $stat = model('clue_log')->field('sum(prices) prices')->where(['mer_id'=>$v['id']])->find();
//            if($stat){
//                $infos[$k]['prices'] = $stat['prices'];
//            }else{
//                $infos[$k]['prices'] = 0;
//            }

            //充值
//            $charge = model('Charge')->field('sum(money) moneys,sum(fz_money) fzmoney')->where(['mer_id'=>$v['id']])->where($map1)->find();
////            $clueMoney = model('ClueLog')->where(['mer_id'=>$v['id']])->where($map1)->sum('price');
//            if($charge){
//                $infos[$k]['moneys'] = $charge['moneys'];
//                $infos[$k]['fzmoney'] = $charge['fzmoney'];
//            }else{
//                $infos[$k]['moneys'] = 0;
//                $infos[$k]['fzmoney'] = 0;
//            }

//            $infos[$k]['prices']=$v['price'];
            $infos[$k]['timeMoney']=bcsub($infos[$k]['moneys'],$infos[$k]['prices'],2);
            $infos[$k]['timeMoney2']=bcsub($infos[$k]['fzmoney'],$infos[$k]['prices'],2);
        }


        return $this->fetch('',[
            'infos' => $infos,
            'mer_name' => $mer_name,
            'mobile' => $mobile,
            'group_id' => $this->group_id,
            'moneys' => $moneys,
            'fzmoney' => $fzmoney,
            'clueall' => $clueMoneyAll,
            'mall' => $mAll,
            'times' => $times,
            'timemoney' => bcsub($moneys,$clueMoneyAll,2),
            'timemoney2' => bcsub($fzmoney,$clueMoneyAll,2),
            'song_item'=>getSongItemDesc(0),
            'orderb'=>$orderb,
            'fwmoney'=>$fwmoney
        ]);
    }

    public function edit()
    {
        $id = input('id');

//        $stat = model('ClueStat')->field('sum(prices) prices')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $prices = $stat['prices'];
//        }else{
//            $prices = 0;
//        }
//
//        $charge = model('Charge')->field('sum(money) moneys')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $moneys = $charge['moneys'];
//        }else{
//            $moneys = 0;
//        }

//        $yue = format_number($moneys - $prices);
        $yue = Db::name('merchant')->where('id',$id)->value('balance');

        return self::showJsonReturnCodeData('1001',['yue'=>$yue],'');
    }

    public function edit2()
    {
        $id = input('id');

//        $stat = model('ClueStat')->field('sum(prices) prices')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $prices = $stat['prices'];
//        }else{
//            $prices = 0;
//        }
//
//        $charge = model('Charge')->field('sum(money) moneys')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $moneys = $charge['moneys'];
//        }else{
//            $moneys = 0;
//        }

//        $yue = format_number($moneys - $prices);
        $yue = Db::name('merchant')->where('id',$id)->value('balance3');

        return self::showJsonReturnCodeData('1001',['yue'=>$yue],'');
    }

    public function getChargeInfo()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $user = model('charge')->getInfoByMap(['id'=>$id]);
        return self::showJsonReturnCodeData('1001',$user,'');
    }


    //编辑修改充值记录
    public function editsave()
    {

        $save_data = input('post.');

        $log=Db::name('charge')->where('id',$save_data['id'])->find();

        $merInfo=Db::name('merchant')->where('id',$log['mer_id'])->find();

        $result = $this->editData(false,'','Charge',$save_data);
        $time=time();
        if($result){

            if($save_data['money']>$log['money']){

                $addMoney=bcsub($save_data['money'],$log['money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setInc('balance',$addMoney);
                $merBalance=bcadd($merInfo['balance'],$addMoney,2);
                $balanceLog[]=['mer_id'=>$log['mer_id'],'change_type'=>1,'type'=>1,'money'=>$addMoney,'balance'=>$merBalance,'create_time'=>$time,'remark'=>'修改'];

            }elseif ($save_data['money']<$log['money']){

                $subMoney=bcsub($log['money'],$save_data['money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setDec('balance',$subMoney);
                $merBalance=bcsub($merInfo['balance'],$subMoney,2);
                $balanceLog[]=['mer_id'=>$log['mer_id'],'change_type'=>2,'type'=>1,'money'=>$subMoney,'balance'=>$merBalance,'create_time'=>$time,'remark'=>'修改'];
            }
            if ($save_data['money'] != $log['money']) {
                $money = bcsub($save_data['money'], $log['money'], 2);
                (new Merchant())->changeBalance($log['mer_id'], $money); //账户余额币 变化 业务逻辑
            }

            if($save_data['fz_money']>$log['fz_money']){

                $addMoney=bcsub($save_data['fz_money'],$log['fz_money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setInc('balance2',$addMoney);
                $merBalance=bcadd($merInfo['balance2'],$addMoney,2);
                $balanceLog[]=['mer_id'=>$log['mer_id'],'change_type'=>1,'type'=>2,'money'=>$addMoney,'balance'=>$merBalance,'create_time'=>$time,'remark'=>'修改'];
            }elseif ($save_data['fz_money']<$log['fz_money']){

                $subMoney=bcsub($log['fz_money'],$save_data['fz_money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setDec('balance2',$subMoney);

                $merBalance=bcsub($merInfo['balance2'],$subMoney,2);
                $balanceLog[]=['mer_id'=>$log['mer_id'],'change_type'=>2,'type'=>2,'money'=>$subMoney,'balance'=>$merBalance,'create_time'=>$time,'remark'=>'修改'];
            }


            if($save_data['fw_money']>$log['fw_money']){

                $addMoney=bcsub($save_data['fw_money'],$log['fw_money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setInc('balance3',$addMoney);

                $merBalance=bcadd($merInfo['balance3'],$addMoney,2);
                $balanceLog[]=['mer_id'=>$log['mer_id'],'change_type'=>1,'type'=>3,'money'=>$addMoney,'balance'=>$merBalance,'create_time'=>$time,'remark'=>'修改'];
            }elseif ($save_data['fw_money']<$log['fw_money']){

                $subMoney=bcsub($log['fw_money'],$save_data['fw_money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setDec('balance3',$subMoney);
                $merBalance=bcsub($merInfo['balance3'],$subMoney,2);
                $balanceLog[]=['mer_id'=>$log['mer_id'],'change_type'=>2,'type'=>3,'money'=>$subMoney,'balance'=>$merBalance,'create_time'=>$time,'remark'=>'修改'];
            }

            if(!empty($balanceLog)){
                Db::name('merchant_balance_log')->insertAll($balanceLog);
            }

        }
        $this->RecordSystemLog($this->uid,$this->behavior,'记录【'.$save_data['id'].'】修改【'.$save_data['money'].'】成功');

//        $stat = model('ClueStat')->field('sum(prices) prices')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $prices = $stat['prices'];
//        }else{
//            $prices = 0;
//        }
//
//        $charge = model('Charge')->field('sum(money) moneys')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $moneys = $charge['moneys'];
//        }else{
//            $moneys = 0;
//        }

//        $yue = format_number($moneys - $prices);

        return self::showJsonReturnCodeData('1001',[],'');
    }

    public function editsave2()
    {

        $save_data = input('post.');

        $log=Db::name('charge_fw')->where('id',$save_data['id'])->find();

        $result = $this->editData(false,'','ChargeFw',$save_data);
        if($result){

            if($save_data['money']>$log['money']){

                $addMoney=bcsub($save_data['money'],$log['money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setInc('balance3',$addMoney);
            }elseif ($save_data['money']<$log['money']){

                $subMoney=bcsub($log['money'],$save_data['money'],2);
                Db::name('merchant')->where('id',$log['mer_id'])->setDec('balance3',$subMoney);
            }

        }
        $this->RecordSystemLog($this->uid,$this->behavior,'记录【'.$save_data['id'].'】修改【'.$save_data['money'].'】成功');

//        $stat = model('ClueStat')->field('sum(prices) prices')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $prices = $stat['prices'];
//        }else{
//            $prices = 0;
//        }
//
//        $charge = model('Charge')->field('sum(money) moneys')->where(['mer_id'=>$id])->find();
//        if($stat){
//            $moneys = $charge['moneys'];
//        }else{
//            $moneys = 0;
//        }

//        $yue = format_number($moneys - $prices);

        return self::showJsonReturnCodeData('1001',[],'');
    }

    //充值
    public function save()
    {

        if(request()->isAjax()){
            Db::startTrans();
            try{
                $save_data = input('post.');
//                dump($save_data);die;
                if(empty($save_data['mer_id'])){
                    throw new \Exception('充值商户不能为空');
                }

//                $bool=$this->tokenBucket($this->uid,'chongzhi_'.$save_data['mer_id'],120,1);
//                if(!$bool){
//                    return $this->showReturnCode(1009,'请勿频繁操作');
//                }

                $save_data['money'] = $save_data['money'] ?? 0;
                $save_data['fz_money'] = $save_data['fz_money'] ?? 0;
                $save_data['fw_money'] = $save_data['fw_money'] ?? 0;

                $result = $this->editData(false,'','Charge',$save_data);
                if($result['code'] == 1001){
                    Db::name('merchant')->where('id',$save_data['mer_id'])->inc('balance',$save_data['money'])->inc('balance2',$save_data['fz_money'])->inc('balance3',$save_data['fw_money'])->update();
                    $merInfo=Db::name('merchant')->where('id',$save_data['mer_id'])->find();
                    if($save_data['money']>0){
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>1,'money'=>floatval($save_data['money']),'balance'=>$merInfo['balance'],'create_time'=>time(),'remark'=>'充值'];
                    }else{
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>2,'type'=>1,'money'=>floatval($save_data['money']),'balance'=>$merInfo['balance'],'create_time'=>time(),'remark'=>'充值'];
                    }

                    if($save_data['fz_money']>0){
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>2,'money'=>floatval($save_data['fz_money']),'balance'=>$merInfo['balance2'],'create_time'=>time(),'remark'=>'充值'];
                    }else{
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>2,'type'=>2,'money'=>floatval($save_data['fz_money']),'balance'=>$merInfo['balance2'],'create_time'=>time(),'remark'=>'充值'];
                    }

                    if($save_data['fw_money']>0){
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>3,'money'=>floatval($save_data['fw_money']),'balance'=>$merInfo['balance3'],'create_time'=>time(),'remark'=>'充值'];
                    }else{
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>2,'type'=>3,'money'=>floatval($save_data['fw_money']),'balance'=>$merInfo['balance3'],'create_time'=>time(),'remark'=>'充值'];
                    }

                    if(!empty($balanceLog)){
                        Db::name('merchant_balance_log')->insertAll($balanceLog);
                    }

                    (new Merchant())->changeBalance($save_data['mer_id'], $save_data['money']); //账户余额币 变化 业务逻辑

                    $result['msg'] = '充值成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'商户【'.$save_data['mer_id'].'】充值【'.json_encode($save_data).'】成功');
                }

                Db::commit();
                return $result;
            } catch (\Exception $e){
                Db::rollback();
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    //赠送
    public function save2()
    {

        if(request()->isAjax()){
            try{
                $save_data = input('post.');
                if(empty($save_data['mer_id'])){
                    return $this->showReturnCode(1009,'赠送商户不能为空');
                }

                if(empty($save_data['song_item'])){
                    return $this->showReturnCode(1009,'请选择赠送原因');
                }

                $bool=$this->tokenBucket($this->uid,'zengsong_'.$save_data['mer_id'],120,1);
                if(!$bool){
                    return $this->showReturnCode(1009,'请勿频繁操作');
                }
                $save_data['type']=2;
                $result = $this->editData(false,'','Charge',$save_data);
                if($result['code'] == 1001){
                    Db::name('merchant')->where('id',$save_data['mer_id'])->setInc('balance',$save_data['money']);
                    $merInfo=Db::name('merchant')->where('id',$save_data['mer_id'])->find();

                    $balanceLog=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>1,'money'=>$save_data['money'],'balance'=>$merInfo['balance'],'create_time'=>time(),'remark'=>'赠送'];
                    Db::name('merchant_balance_log')->insert($balanceLog);

                    (new Merchant())->changeBalance($save_data['mer_id'], $save_data['money']); //账户余额币变化 业务逻辑

                    $result['msg'] = '赠送成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'商户【'.$save_data['mer_id'].'】赠送【'.$save_data['money'].'】成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function save3()
    {

        if(request()->isAjax()){
            try{
                $save_data = input('post.');
                if(empty($save_data['mer_id'])){
                    return $this->showReturnCode(1009,'充值商户不能为空');
                }

                $bool=$this->tokenBucket($this->uid,'chongzhi_'.$save_data['mer_id'],120,1);
                if(!$bool){
                    return $this->showReturnCode(1009,'请勿频繁操作');
                }
                $result = $this->editData(false,'','ChargeFw',$save_data);
                if($result['code'] == 1001){
                    Db::name('merchant')->where('id',$save_data['mer_id'])->setInc('balance3',$save_data['money']);
                    $result['msg'] = '充值成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'商户【'.$save_data['mer_id'].'】充值服务币【'.$save_data['money'].'】成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function edit_prices()
    {
        if(request()->isAjax()){
            try{
                $save_data = input('post.');

                $stat = Db::name('clue_stat')->find($save_data['id']);

                $result = $this->editData(false,'','ClueStat',$save_data);
                if($result['code'] == 1001){
                    $result['msg'] = '修改成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'消耗统计【'.$save_data['id'].'】原金额【'.$stat['prices'].'】修改为【'.$save_data['prices'].'】成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }


    //消耗明细
    public function clue_log()
    {
        // 查询条件start
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $times = input('times','');
        $mer_id = input('param.mer_id','');

        $map['mer_id'] = $mer_id;
        if($clue_name != ''){
            $map['clue_name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != 0){
            $map['phone'] = $phone;
        }
        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }
        // 查询条件end

        $infos = model('ClueLog')->getInfosByMap($map, '', false);

        foreach ($infos as $k=>$v){
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }

            $product = model('Product')->field('name')->where(['id'=>$v['pro_id']])->find();
            $merchant = model('Merchant')->field('mer_name,username,phone,mer_desc')->where(['id'=>$v['mer_id']])->find();
            $account = model('Account')->field('acc_name,acc_desc')->where(['adv_id'=>$v['adv_id']])->find();
            $infos[$k]['acc_name'] = $account['acc_name'];
            $infos[$k]['acc_desc'] = $account['acc_desc'];
            $infos[$k]['pro_name'] = $product['name'];
            $infos[$k]['mer_name'] = $merchant['mer_name'];
            $infos[$k]['username'] = $merchant['username'];
            $infos[$k]['mer_phone'] = $merchant['phone'];
            $infos[$k]['mer_desc'] = $merchant['mer_desc'];
            $infos[$k]['charge_type'] = config('clue.charge_types')[$v['charge_type']];
            $infos[$k]['progress'] = model('ClueProgress')->where('clue_log_id',$v['id'])->order('id desc')->select();
        }
        $province = Db::name('city')->where(['pid'=>1])->select();
        return $this->fetch('clue_log/index',[
            'infos' => $infos,
            'clue_name' => $clue_name,
            'phone' => $phone,
            'times' => $times,
            'clue_id' => '',
            'sprovince' => '',
            'scity' => '',
            'province' => $province,
            'mer_name' => '',
            'ac_name' => '',
            'adv_id' => '',
        ]);
    }


    // 消耗明细统计
    public function consume()
    {
        $adv_id = input('adv_id','');
        $mer_id = input('mer_id','');
        $pro_id = input('pro_id','');
        $cityname = input('cityname','');
//        $times = input('time',date('Y-m-d', strtotime('-1 days')).' 00:00:00 - '.date('Y-m-d').' 00:00:00');
        $times = input('time');

        $map=[];
        if($adv_id != ''){
            if($adv_id == '9999'){
                $map['a.adv_id'] = '';
            }else{
                $map['a.adv_id'] = $adv_id;
            }
        }
        if($mer_id != ''){
            $map['a.mer_id'] = $mer_id;
        }
        if($pro_id!=''){
            $map['c.pro_id']=$pro_id;
        }

        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['c.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['c.city']=0;
            }
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['a.time'] = ['between',[$time_arr[0],$time_arr[1]]];
        }

        // 不是开发者或者超级管理员则只能看自己的数据
        if(in_array($this->group_id,[4,5])){
            $accounts=[];
            $map1['bind_aid|weihu_aid']=$this->uid;
            $map1['status']=1;
            $merchants = model('Merchant')->getListByMapAndOrder($map1, '', '',true,'id desc');
            $mArr=array_column($merchants,'id');
            if($mArr){
                if(!in_array($mer_id,$mArr)){
                    $map['a.mer_id']=['in',$mArr];
                }else{
                    $map['a.mer_id']=$mer_id;
                }
            }else{
                $map['a.mer_id']=0;
            }
        }else{
            $where_account = [];
            if($this->uid != 1 && $this->group_id != 1){
                $where_account['admin_id'] = $this->uid;
            }
            $accounts = model('Account')->getListByMapAndOrder($where_account, '', '',true,'id desc');
            $merchants = model('Merchant')->getListByMapAndOrder([], '', '',true,'id desc');
        }


        $infos = model('ClueStat')->alias('a')->field('a.*,b.mer_name,c.city,c.pro_id')
            ->join('merchant b','b.id=a.mer_id','LEFT')
            ->join('push c','c.id=a.push_id','LEFT')
            ->where($map)
            ->order('a.id desc')
            ->paginate();

        $total = model('ClueStat')->alias('a')
            ->join('merchant b','b.id=a.mer_id','LEFT')
            ->join('push c','c.id=a.push_id','LEFT')
            ->field('sum(clue_num) clue_num,sum(clue_dis_num) clue_dis_num,sum(prices) prices')->where($map)->find();

        $productAll =Db::name('product')->column('name','id');
        $products = model('Product')->where('status',1)->column('name','id');

        foreach ($infos as $k=>$v){
            $account = model('Account')->field('acc_name')->where(['adv_id'=>$v['adv_id']])->find();
            $infos[$k]['acc_name'] = $account['acc_name'] ?? '';
            $infos[$k]['pro_name'] = $productAll[$v['pro_id']];
            $infos[$k]['charge_type'] = config('clue.charge_types')[$v['charge_type']];
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }else{
                $infos[$k]['city'] = '';
            }
        }

        return $this->fetch('',[
            'infos' => $infos,
            'accounts' => $accounts,
            'merchants' => $merchants,
            'time' => $times,
            'adv_id' => $adv_id,
            'mer_id' => $mer_id,
            'group_id' => $this->group_id,
            'clue_num' => isset($total['clue_num'])?$total['clue_num']:0,
            'clue_dis_num' => isset($total['clue_dis_num'])?$total['clue_dis_num']:0,
            'prices' => isset($total['prices'])?$total['prices']:0,
            'pro_id' => $pro_id,
            'cityname' => $cityname,
            'products' => $products,
        ]);
    }


    // 充值明细
    public function charge()
    {
        $mer_id = input('mer_id','');
        $type = input('type','');
        $times = input('times','');
        $map = [];
        if($mer_id != ''){
            $map['mer_id'] = $mer_id;
        }

        if(in_array($this->group_id,[4,5])){
            $map1['bind_aid|weihu_aid']=$this->uid;
            $map1['status']=1;
            $mArr=model('merchant')->where($map1)->column('id');
            if($mArr){
                if(!in_array($mer_id,$mArr)){
                    $map['mer_id']=['in',$mArr];
                }else{
                    $map['mer_id']=$mer_id;
                }
            }else{
                $map['mer_id']=0;
            }
        }
        if($type){
            $map['type']=$type;
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }

        $infos = model('Charge')->getInfosByMap($map, '', false);

        foreach ($infos as $k=>$v){
            $merchant = model('Merchant')->field('mer_name')->where(['id'=>$v['mer_id']])->find();
            $infos[$k]['mer_name'] = $merchant['mer_name'];
            if($v['type']==1){
                $infos[$k]['type']='充值';
                $infos[$k]['song_item']='';

            }elseif($v['type']==2){
                $infos[$k]['type']='赠送';
                $infos[$k]['song_item']=getSongItemDesc($v['song_item']);
            }

        }

        return $this->fetch('',[
            'infos' => $infos,
            'group_id' => $this->group_id,
            'times' => $times,
        ]);
    }

    public function charge2()
    {
        $mer_id = input('mer_id','');
        $type = input('type','');
        $times = input('times','');
        $map = [];
        if($mer_id != ''){
            $map['mer_id'] = $mer_id;
        }

        if(in_array($this->group_id,[4,5])){
            $map1['bind_aid|weihu_aid']=$this->uid;
            $map1['status']=1;
            $mArr=model('merchant')->where($map1)->column('id');
            if($mArr){
                if(!in_array($mer_id,$mArr)){
                    $map['mer_id']=['in',$mArr];
                }else{
                    $map['mer_id']=$mer_id;
                }
            }else{
                $map['mer_id']=0;
            }
        }
        if($type){
            $map['type']=$type;
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }

        $infos = model('ChargeFw')->getInfosByMap($map, '', false);

        foreach ($infos as $k=>$v){
            $merchant = model('Merchant')->field('mer_name')->where(['id'=>$v['mer_id']])->find();
            $infos[$k]['mer_name'] = $merchant['mer_name'];
            if($v['type']==1){
                $infos[$k]['type']='充值';
                $infos[$k]['song_item']='';

            }elseif($v['type']==2){
                $infos[$k]['type']='赠送';
                $infos[$k]['song_item']=getSongItemDesc($v['song_item']);
            }

        }

        return $this->fetch('',[
            'infos' => $infos,
            'group_id' => $this->group_id,
            'times' => $times,
        ]);
    }


    // 线索统计
    public function clue()
    {
        $map = [];
        $adv_id = input('adv_id','');
        if($adv_id != ''){
            if($adv_id == '9999'){
                $map['adv_id'] = '';
            }else{
                $map['adv_id'] = $adv_id;
            }
        }
        // 不是开发者或者超级管理员则只能看自己的数据
        $where_account = [];
        if($this->uid != 1 && $this->group_id != 1){
            $where_account['admin_id'] = $this->uid;
        }
        $accounts = model('Account')->getListByMapAndOrder($where_account, '', '',true,'id desc');
        $infos = model('Clue')->field('adv_id,city,count(id) clue_accept')->where($map)->group('adv_id,city')->paginate();
        foreach ($infos as $k=>$v){
            $account = model('Account')->field('acc_name')->where(['adv_id'=>$v['adv_id']])->find();
            $infos[$k]['acc_name'] = $account['acc_name'] ?? '【手动添加的线索】';
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }else{
                $infos[$k]['city'] = '';
            }
            $log = model('ClueLog')->field('count(id) clue_push')->where(['status'=>1,'adv_id'=>$v['adv_id'],'city'=>$v['city']])->find();
            if($log){
                $infos[$k]['clue_push'] = $log['clue_push'];
            }else{
                $infos[$k]['clue_push'] = 0;
            }
        }

        return $this->fetch('',[
            'infos' => $infos,
            'accounts' => $accounts,
            'adv_id' => $adv_id,
        ]);
    }

    public function give()
    {
        $mer_name = input('mer_name','');
        $times = input('times','');
        $orderb = input('orderb','');
        $type = input('type',1);

        $map = [];
        $map1 = [];
        $map2 = [];
        $map3 = [];
        $map4 = '';
        $map5 = '';
        $map6 = '';

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1]).' 23:59:59']];
        }

        if(in_array($this->group_id,[4,5])){
            $map['bind_aid|weihu_aid']=$this->uid;
        }

        if($mer_name != ''){
            $map['mer_name'] = ['like','%'.$mer_name.'%'];

        }

        $orderDef='a.id asc';
        if ($orderb==5){
            $orderDef='money asc';
        }elseif ($orderb==6){
            $orderDef='money desc';
        }elseif ($orderb==7){
            $orderDef='fz_money asc';
        }elseif ($orderb==8){
            $orderDef='fz_money desc';
        }

        if($type==1){
            $infos=model('Charge')->alias('a')->field('a.mer_id,b.mer_name,b.mer_desc,b.phone,b.username,sum(money) money,sum(fz_money) fz_money')
                ->join('merchant b','b.id=a.mer_id')
                ->where($map)->group('a.mer_id')->order($orderDef)->paginate();
            $total=model('Charge')->alias('a')->field('sum(money) money,sum(fz_money) fz_money')
                ->join('merchant b','b.id=a.mer_id')
                ->where($map)->find();
        }else{
            $infos=model('Charge')->alias('a')->field('a.mer_id,c.city,b.mer_name,b.mer_desc,b.phone,b.username,sum(money) money,sum(fz_money) fz_money')
                ->join('merchant b','b.id=a.mer_id')
                ->join('push c','b.id=c.mer_id')
                ->where($map)->group('c.city')->order($orderDef)->paginate();
//            $total=model('Charge')->alias('a')->field('sum(money) money,sum(fz_money) fz_money')
//                ->join('merchant b','b.id=a.mer_id')
//                ->join('push c','b.id=c.mer_id')
//                ->where($map)->find();
        }


        foreach ($infos as &$v){
            if($type==1){
                $v['city']='';
            }else{
                if($v['city'] != ''){
                    $ids = explode('-',$v['city']);
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $v['city'] = $prov;
                    }else{
                        $v['city'] = $prov.'-'.$city;
                    }
                }
            }
            $v['song']=bcsub($v['money'],$v['fz_money'],2);
            if($v['fz_money']>0){
                $v['song_rate']=bcdiv($v['song'],$v['fz_money'],4)*100;
            }else{
                $v['song_rate']=0;
            }
        }

        $moneys=!empty($total['money'])?$total['money']:0;
        $fzmoney=!empty($total['fz_money'])?$total['fz_money']:0;
        $song=bcsub($moneys,$fzmoney,2);
        if($fzmoney>0){
            $songRate=bcdiv($song,$fzmoney,4)*100;
        }else{
            $songRate=0;
        }


        return $this->fetch('',[
            'infos' => $infos,
            'mer_name' => $mer_name,
            'group_id' => $this->group_id,
            'moneys' => $moneys,
            'fzmoney' => $fzmoney,
            'song' => $song,
            'song_rate' => $songRate,
            'times' => $times,
            'type' => $type,
            'orderb'=>$orderb
        ]);
    }
}